import { createWebHistory, createRouter } from 'vue-router'

import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import http from '../utils/http.js';
import sysStore from '../store/modules/sys.js'
import dictStore from '../store/modules/dict.js'
import api from '../api/api.js';

NProgress.configure({
	showSpinner: false
});

const constantRoutes = [
	
	{
		name: "login",
		path: "/login",
		component: () => import("@/view/login/Login.vue")
	},

	{
		name: "home",
		path: "/home",
		component: () => import("@/view/home/Home.vue"),
		redirect: '/index',
		children: [{
			name: "index",
			path: "/index",
			component: () => import("@/view/index/Index.vue"),
			meta: {
				title: '首页',
				affix: true
			}
		}, 
		{
			name: "sysProfile",
			path: "/sysProfile",
			component: () => import("@/view/sys/user/profile.vue"),
			meta: {
				title: '个人中心'
			}
		},
		]
	},
	
	{
		path: "/",
		redirect: "/login"
	},
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    }
    return { top: 0 }
  },
});

const whiteList = ['/login']
//挂载路由导航守卫
router.beforeEach((to, from, next) => {
	NProgress.start();

	if (http.getToken()) {
		// to.meta.title && sysStore().setTitle(to.meta.title)
		/* has token*/
		if (to.path === '/login') {
			next({
				path: '/index'
			})
		} else {
			if (sysStore().menuList == null) {
				sysStore().generateRoutes().then(accessRoutes => {
					// 根据roles权限生成可访问的路由表
					console.error("accessRoutes", accessRoutes)
					accessRoutes.forEach((item) => {
						router.addRoute("home", {
							name: item.name,
							path: item.path,
							component: item.component,
							meta: {
								title: item.name,
								affix: false
							}
						})
					})
					dictStore().initDict()
					api.sysUserFindProfile().then(data=>{
						next({
							...to,
							replace: true
						}) // hack方法 确保addRoutes已完成
						sysStore().updateUserInfo(data);
					})
				})
			} else {
				next()
			}
		}
	} else {
		// 没有token
		if (whiteList.indexOf(to.path) !== -1) {
			// 在免登录白名单，直接进入
			next()
		} else {
			next(`/login`) // 否则全部重定向到登录页
		}
	}
});

router.afterEach(() => {
	NProgress.done();
	window.scrollTo(0, 0);
});

export default router;